const inquirer = require("inquirer");
const chalk = require("chalk");
const GiteeClient = require("./gitee");
const CodeDownloader = require("./downloader");

/**
 * 命令行交互界面类
 */
class CLI {
  constructor() {
    this.giteeClient = new GiteeClient();
    this.downloader = new CodeDownloader();
  }

  /**
   * 显示欢迎信息
   */
  showWelcome() {
    console.log(chalk.cyan.bold("\n TYG CLI - Gitee代码包拉取工具\n"));
  }

  /**
   * 主菜单
   */
  async showMainMenu() {
    const { action } = await inquirer.prompt([
      {
        type: "list",
        name: "action",
        message: "请选择操作:",
        choices: [
          // { name: "搜索仓库", value: "search" },
          // { name: "浏览用户仓库", value: "user" },
          { name: "直接下载仓库", value: "direct" },
          // { name: "⚙️  设置访问令牌", value: "token" },
          { name: "❌ 退出", value: "exit" },
        ],
      },
    ]);
    return action;
  }

  /**
   * 搜索仓库
   */
  async searchRepositories() {
    const { keyword, language, sort } = await inquirer.prompt([
      {
        type: "input",
        name: "keyword",
        message: "请输入搜索关键词:",
        validate: (input) => (input.trim() ? true : "请输入有效的搜索关键词"),
      },
      {
        type: "input",
        name: "language",
        message: "编程语言 (可选):",
        default: "",
      },
      {
        type: "list",
        name: "sort",
        message: "排序方式:",
        choices: [
          { name: "最新更新", value: "updated" },
          { name: "最多星标", value: "stars" },
          { name: "最多Fork", value: "forks" },
        ],
        default: "updated",
      },
    ]);

    try {
      const options = {
        language: language.trim() || null,
        sort: sort,
        perPage: 20,
      };

      const repositories = await this.giteeClient.searchRepositories(
        keyword,
        options
      );

      if (repositories.length === 0) {
        console.log(chalk.yellow("未找到匹配的仓库"));
        return;
      }

      return await this.selectRepository(repositories);
    } catch (error) {
      console.error(chalk.red("搜索失败:"), error.message);
    }
  }

  /**
   * 浏览用户仓库
   */
  async browseUserRepositories() {
    const { username, type } = await inquirer.prompt([
      {
        type: "input",
        name: "username",
        message: "请输入用户名:",
        validate: (input) => (input.trim() ? true : "请输入有效的用户名"),
      },
      {
        type: "list",
        name: "type",
        message: "仓库类型:",
        choices: [
          { name: "所有仓库", value: "all" },
          { name: "公开仓库", value: "public" },
          { name: "私有仓库", value: "private" },
        ],
        default: "all",
      },
    ]);

    try {
      const repositories = await this.giteeClient.getUserRepositories(
        username,
        {
          type: type,
          perPage: 50,
        }
      );

      if (repositories.length === 0) {
        console.log(chalk.yellow("该用户没有仓库或仓库不可访问"));
        return;
      }

      return await this.selectRepository(repositories);
    } catch (error) {
      console.error(chalk.red("获取用户仓库失败:"), error.message);
    }
  }

  /**
   * 直接下载仓库
   */
  async directDownload() {
    const { repoUrl } = await inquirer.prompt([
      {
        type: "input",
        name: "repoUrl",
        message: "请输入仓库URL (例如: https://gitee.com/owner/repo):",
        default: "https://gitee.com/gaspar1986/vue3-template",
        validate: (input) => {
          const trimmed = input.trim();
          if (!trimmed) return "请输入有效的仓库URL";

          // 支持多种格式
          if (trimmed.includes("/") || trimmed.includes("gitee.com")) {
            return true;
          }
          return "请输入有效的仓库URL格式";
        },
      },
    ]);

    try {
      let owner, repo;

      if (repoUrl.includes("gitee.com")) {
        // 从完整URL解析
        const match = repoUrl.match(/gitee\.com\/([^\/]+)\/([^\/]+)/);
        if (match) {
          owner = match[1];
          repo = match[2].replace(".git", "");
        } else {
          throw new Error("无法解析仓库URL");
        }
      } else {
        // 从 owner/repo 格式解析
        const parts = repoUrl.split("/");
        if (parts.length !== 2) {
          throw new Error("仓库URL格式错误，请使用 owner/repo 格式");
        }
        owner = parts[0];
        repo = parts[1];
      }

      const repository = await this.giteeClient.getRepository(owner, repo);
      return await this.downloadRepository(repository);
    } catch (error) {
      console.error(chalk.red("获取仓库信息失败:"), error.message);
    }
  }

  /**
   * 选择仓库
   */
  async selectRepository(repositories) {
    const choices = repositories.map((repo) => ({
      name: `${chalk.cyan(repo.full_name)} - ${chalk.gray(
        repo.description || "无描述"
      )}`,
      value: repo,
      short: repo.full_name,
    }));

    const { selectedRepo } = await inquirer.prompt([
      {
        type: "list",
        name: "selectedRepo",
        message: "请选择要下载的仓库:",
        choices: choices,
        pageSize: 10,
      },
    ]);

    return await this.downloadRepository(selectedRepo);
  }

  /**
   * 下载仓库
   */
  async downloadRepository(repository) {
    // 获取仓库的默认分支
    const defaultBranch = repository.default_branch || "master";

    const { downloadMethod, targetDir, branch } = await inquirer.prompt([
      {
        type: "list",
        name: "downloadMethod",
        message: "选择下载方式:",
        choices: [
          { name: "Git克隆", value: "clone" },
          // { name: "下载ZIP包", value: "zip" },
        ],
        default: "clone",
      },
      {
        type: "input",
        name: "targetDir",
        message: "目标目录:",
        default: `./${repository.name}`,
        validate: (input) => (input.trim() ? true : "请输入有效的目录路径"),
      },
      {
        type: "input",
        name: "branch",
        message: `分支/标签 (默认: ${defaultBranch}):`,
        default: defaultBranch,
      },
    ]);

    try {
      let resultPath;

      if (downloadMethod === "zip") {
        resultPath = await this.downloader.downloadZip(
          repository.owner.login,
          repository.name,
          targetDir,
          { branch: branch }
        );
      } else {
        const cloneUrl = this.downloader.getCloneUrl(
          repository.owner.login,
          repository.name
        );
        resultPath = await this.downloader.cloneRepository(
          cloneUrl,
          targetDir,
          { branch: branch }
        );
      }

      console.log(chalk.green.bold("\n✅ 下载完成!"));
      console.log(chalk.cyan(`项目路径: ${resultPath}`));
      return resultPath;
    } catch (error) {
      console.error(chalk.red("下载失败:"), error.message);
    }
  }

  /**
   * 设置访问令牌
   */
  async setAccessToken() {
    const { token } = await inquirer.prompt([
      {
        type: "password",
        name: "token",
        message: "请输入Gitee访问令牌 (可选，用于访问私有仓库):",
        mask: "*",
      },
    ]);

    if (token.trim()) {
      this.giteeClient.setAccessToken(token.trim());
      console.log(chalk.green("访问令牌设置成功"));
    } else {
      console.log(chalk.yellow("未设置访问令牌，只能访问公开仓库"));
    }
  }

  /**
   * 运行CLI
   */
  async run() {
    this.showWelcome();

    while (true) {
      try {
        const action = await this.showMainMenu();

        switch (action) {
          case "search":
            await this.searchRepositories();
            break;
          case "user":
            await this.browseUserRepositories();
            break;
          case "direct":
            await this.directDownload();
            break;
          case "token":
            await this.setAccessToken();
            break;
          case "exit":
            console.log(chalk.cyan("\n 感谢使用 TYG CLI!"));
            process.exit(0);
        }

        // 询问是否继续
        const { continue: shouldContinue } = await inquirer.prompt([
          {
            type: "confirm",
            name: "continue",
            message: "是否继续使用?",
            default: true,
          },
        ]);

        if (!shouldContinue) {
          console.log(chalk.cyan("\n 感谢使用 TYG CLI!"));
          process.exit(0);
        }
      } catch (error) {
        console.error(chalk.red("发生错误:"), error.message);
      }
    }
  }
}

module.exports = CLI;
